﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;//ip格式

using System.IO;
using System.Collections;

using System.Security.Cryptography;
using System.Data.OleDb;
using System.Data;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using Sunny.UI;


namespace LaneLpnr.Common
{
    public class utils
    {
        public static bool IsRightIP(string strLocalIP)
        {
            bool bFlag = false;
            bool Result = true;

            Regex regex = new Regex("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
            bFlag = regex.IsMatch(strLocalIP);
            if (bFlag == true)
            {
                string[] strTemp = strLocalIP.Split(new char[] { '.' });
                int nDotCount = strTemp.Length - 1; //字符串中.的数量，若.的数量小于3，则是非法的ip地址
                if (3 == nDotCount)//判断 .的数量
                {
                    for (int i = 0; i < strTemp.Length; i++)
                    {
                        if (Convert.ToInt32(strTemp[i]) > 255)   //大于255不符合返回false
                        {
                            Result = false;
                        }
                    }
                }
                else
                {
                    Result = false;
                }
            }
            else
            {
                //输入非数字则提示，不符合IP格式
                //MessageBox.Show("不符合IP格式");
                Result = false;
            }
            return Result;

        }





        //C#快速获取JPG图片大小及英寸分辨率
        public static int getJpgSize(string FileName, out Size JpgSize, out float Wpx, out float Hpx)
        {//C#快速获取JPG图片大小及英寸分辨率
            JpgSize = new Size(0, 0);
            Wpx = 0; Hpx = 0;
            int rx = 0;
            if (!File.Exists(FileName)) return rx;
            FileStream F_Stream = File.OpenRead(FileName);
            int ff = F_Stream.ReadByte();
            int type = F_Stream.ReadByte();
            if (ff != 0xff || type != 0xd8)
            {//非JPG文件
                F_Stream.Close();
                return rx;
            }
            long ps = 0;
            do
            {
                do
                {
                    ff = F_Stream.ReadByte();
                    if (ff < 0) //文件结束
                    {
                        F_Stream.Close();
                        return rx;
                    }
                } while (ff != 0xff);

                do
                {
                    type = F_Stream.ReadByte();
                } while (type == 0xff);

                //MessageBox.Show(ff.ToString() + "," + type.ToString(), F_Stream.Position.ToString());
                ps = F_Stream.Position;
                switch (type)
                {
                    case 0x00:
                    case 0x01:
                    case 0xD0:
                    case 0xD1:
                    case 0xD2:
                    case 0xD3:
                    case 0xD4:
                    case 0xD5:
                    case 0xD6:
                    case 0xD7:
                        break;
                    case 0xc0: //SOF0段
                        ps = F_Stream.ReadByte() * 256;
                        ps = F_Stream.Position + ps + F_Stream.ReadByte() - 2; //加段长度

                        F_Stream.ReadByte(); //丢弃精度数据
                        //高度
                        JpgSize.Height = F_Stream.ReadByte() * 256;
                        JpgSize.Height = JpgSize.Height + F_Stream.ReadByte();
                        //宽度
                        JpgSize.Width = F_Stream.ReadByte() * 256;
                        JpgSize.Width = JpgSize.Width + F_Stream.ReadByte();
                        //后面信息忽略
                        if (rx != 1 && rx < 3) rx = rx + 1;
                        break;
                    case 0xe0: //APP0段
                        ps = F_Stream.ReadByte() * 256;
                        ps = F_Stream.Position + ps + F_Stream.ReadByte() - 2; //加段长度

                        F_Stream.Seek(5, SeekOrigin.Current); //丢弃APP0标记(5bytes)
                        F_Stream.Seek(2, SeekOrigin.Current); //丢弃主版本号(1bytes)及次版本号(1bytes)
                        int units = F_Stream.ReadByte(); //X和Y的密度单位,units=0：无单位,units=1：点数/英寸,units=2：点数/厘米

                        //水平方向(像素/英寸)分辨率
                        Wpx = F_Stream.ReadByte() * 256;
                        Wpx = Wpx + F_Stream.ReadByte();
                        if (units == 2) Wpx = (float)(Wpx * 2.54); //厘米变为英寸
                        //垂直方向(像素/英寸)分辨率
                        Hpx = F_Stream.ReadByte() * 256;
                        Hpx = Hpx + F_Stream.ReadByte();
                        if (units == 2) Hpx = (float)(Hpx * 2.54); //厘米变为英寸
                        //后面信息忽略
                        if (rx != 2 && rx < 3) rx = rx + 2;
                        break;

                    default: //别的段都跳过////////////////
                        ps = F_Stream.ReadByte() * 256;
                        ps = F_Stream.Position + ps + F_Stream.ReadByte() - 2; //加段长度
                        break;
                }
                if (ps + 1 >= F_Stream.Length) //文件结束
                {
                    F_Stream.Close();
                    return rx;
                }
                F_Stream.Position = ps; //移动指针
            } while (type != 0xda); // 扫描行开始
            F_Stream.Close();
            return rx;
        }


        /// <summary>
        /// 修改图片分辨率
        /// </summary>
        /// <param name="srcPath">源文件</param>
        /// <param name="desFold">新目录</param>
        /// <param name="width">像素宽度</param>
        /// <param name="flag">图片质量</param>
        public static string Image_Resize(string srcPath, string desFold, int width, int flag)
        {
            try
            {
                string currentPath = desFold;
                string fileName = srcPath.Substring(srcPath.LastIndexOf("\\") + 1, srcPath.Length - srcPath.LastIndexOf("\\") - 1);

                string newFileName = "new" + fileName;

                Image img = Image.FromFile(srcPath);

                //以下代码为保存图片时，设置压缩质量  
                EncoderParameters ep = new EncoderParameters();
                long[] qy = new long[1];
                qy[0] = flag;//设置压缩的比例1-100  
                EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
                ep.Param[0] = eParam;

                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }

                Image newImg = new Bitmap(width, img.Height);

                Graphics grap = Graphics.FromImage(newImg);
                grap.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
                grap.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
                grap.DrawImage(img, 0, 0, width, img.Height);

                if (jpegICIinfo != null)
                {
                    newImg.Save(currentPath + "\\" + newFileName, jpegICIinfo, ep);

                }

                img.Dispose();
                newImg.Dispose();
                return currentPath + "\\" + newFileName;
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常Image_Resize" + ex.ToString());
                return "";
            }
        }




        public static void ShowPicFunction(PictureBox pt, string strPath)
        {
            try
            {
                if (strPath != string.Empty)
                {
                    FlashLog.FlashLogger.Info("ShowPicFunction 路径: " + strPath);
                    FileInfo finfo = new FileInfo(strPath);
                    if (finfo.Exists)
                    {
                        showpichandle(pt, strPath);
                    }
                    else
                    {
                        FlashLog.FlashLogger.Info("文件不存在");
                    }
                }
                else if (strPath == "" || string.IsNullOrEmpty(strPath))
                {
                    showpichandle(pt, "无");
                }

            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Debug("异常ShowPicFunction " + ex.ToString());
            }

        }


        /// <summary>
        /// 跨线程显示至textbox
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="str"></param>
        public static void showhandle(Sunny.UI.UITextBox bt, string str)
        {
            try
            {
                if (bt.InvokeRequired)
                {
                    if (bt != null)
                    {
                        if (str != null)
                        {
                            // 当一个控件的InvokeRequired属性值为真时，说明有一个创建它以外的线程想访问它
                            Action<string> actionDelegate = (x) => {
                                bt.Text = x.ToString();
                            };
                            // 或者
                            // Action<string> actionDelegate = delegate(string txt) { this.label2.Text = txt; };
                            bt.Invoke(actionDelegate, str);
                        }
                        else
                        {
                            bt.Text = str.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Error("showhandle 异常 " + ex.ToString());
            }
        }

        /// <summary>
        /// 跨线程显示至textbox
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="str"></param>
        public static void showTextboxAppend_handle(Sunny.UI.UITextBox bt, string str)
        {
            try
            {
                if (bt.InvokeRequired)
                {
                    if (bt != null)
                    {
                        if (str != null)
                        {
                            // 当一个控件的InvokeRequired属性值为真时，说明有一个创建它以外的线程想访问它
                            Action<string> actionDelegate = (x) => {
                                bt.AppendText( x.ToString());
                            };
                            // 或者
                            // Action<string> actionDelegate = delegate(string txt) { this.label2.Text = txt; };
                            bt.Invoke(actionDelegate, str);
                        }
                        else
                        {
                            bt.AppendText(str);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Error("showhandle 异常 " + ex.ToString());
            }
        }



        /// <summary>
        /// 跨线程显示至picturebox
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="str"></param>
        public static void showpichandle(PictureBox bt, string fileName)
        {
            try
            {
                if (bt.InvokeRequired)
                {
                    // 当一个控件的InvokeRequired属性值为真时，说明有一个创建它以外的线程想访问它
                    Action<string> actionDelegate = (x) =>
                    {
                        FlashLog.FlashLogger.Info("Utils showpichandle file " + fileName);
                        if (bt != null)
                        {
                            if (fileName == "无")
                            {
                                bt.Image = null; bt.Refresh();
                            }
                            else if (fileName != null && fileName != String.Empty)
                            {
                                //string fileName = @str;
                                //string fileName = @"F:\photo\电子签名\1083.gif";
                                FlashLog.FlashLogger.Info("Utils showpichandle file " + fileName);
                                FileStream fs = new FileStream(fileName, FileMode.Open);
                                byte[] byData = new byte[fs.Length];
                                fs.Read(byData, 0, byData.Length);
                                fs.Close();
                                MemoryStream ms = new MemoryStream(byData);
                                Bitmap img = new Bitmap(ms);
                                bt.Image = img;
                                ms.Dispose();
                            }
                            else
                            {
                                bt.Image = null;
                            }
                        }
                    };

                    bt.Invoke(actionDelegate, fileName);
                }
                else
                {
                    if (bt != null)
                    {
                        if (fileName == "无")
                        {
                            bt.Image = null; bt.Refresh();
                        }
                        else if (fileName != null && fileName != String.Empty)
                        {

                            FileStream fs = new FileStream(fileName, FileMode.Open);
                            byte[] byData = new byte[fs.Length];
                            fs.Read(byData, 0, byData.Length);
                            fs.Close();
                            MemoryStream ms = new MemoryStream(byData);
                            Bitmap img = new Bitmap(ms);
                            bt.Image = img;
                            ms.Dispose();
                        }
                        else
                        {
                            bt.Image = null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FlashLog.FlashLogger.Error("showhandle 异常" + ex.ToString() + "  参数为" + bt.ToString() + " " + fileName);
            }
            finally
            {
                GC.Collect();
            }
        }








    }
}
